/*
 * Copyright 2004 original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jbfilter.hibernate;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.jbfilter.core.FilterHandler;
import org.jbfilter.impl.HibernateCallback;
import org.jbfilter.impl.HibernateTemplate;

/**
 * The filter handler for {@link FilterHibernate}'s.
 * To filter the following properties must be set :
 * <ul>
 * <li>{@code class}
 * <li>{@code session} or {@code sessionFactory}
 * </ul>
 * @author Marcus Adrian
 * @param <E> the type of the beans to filter
 */
public class FilterHandlerHibernate<E> implements FilterHandler<E> {
	private FilterHibernate<E> filter;
	
	private Class<E> clazz;
	private Session session;
	private SessionFactory sessionFactory;
	private HibernateTemplate template;
	
	public FilterHandlerHibernate(FilterHibernate<E> filter) {
		this.filter = filter;
	}
	@Override
	public List<E> filter() {
		if (clazz == null) {
			throw new IllegalStateException("class must be set via setClass() or setClassName method prior to filter method call.");
		}
		if (session != null) {
			return filter.filter(clazz, session);
		} else if (sessionFactory != null) {
			return template.execute(new HibernateCallback<List<E>>() {
				public List<E> doInHibernate(Session session) {
					return filter.filter(clazz, session);
				}});
		} else {
			throw new IllegalStateException("session or sessionFactory must be set prior to filter method call.");
		}
	}
	public void setClass(Class<E> clazz) {
		this.clazz = clazz;
	}
	@SuppressWarnings("unchecked")
	public void setClassName(String className) throws ClassNotFoundException {
		clazz = (Class<E>) Class.forName(className);
	}
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
		template = new HibernateTemplate(sessionFactory);
	}

}
